package com.nbsaas.boot.interceptor;

import com.nbsaas.boot.monitor.ApiLogEvent;
import com.nbsaas.boot.monitor.ApiMonitorDisruptor;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

//@Component
@RequiredArgsConstructor
public class ApiMonitorFilter extends OncePerRequestFilter {

    private final ApiMonitorDisruptor disruptor;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        long start = System.currentTimeMillis();
        try {
            filterChain.doFilter(request, response);
        } finally {
            long duration = System.currentTimeMillis() - start;

            ApiLogEvent log = new ApiLogEvent();
            log.setUri(request.getRequestURI());
            log.setMethod(request.getMethod());
            log.setStartTime(start);
            log.setDuration(duration);
            log.setStatus(response.getStatus());
            log.setSuccess(response.getStatus() < 400);
            log.setTenantId(request.getHeader("X-Tenant-Id")); // 多租户Header支持

            disruptor.publish(log); // 非阻塞上报
        }
    }
}
